from utils.redis_tool import RedisTool
import json  # python 内置的，re,os,time


class CacheTool(RedisTool):
    # 把数据转换为json
    def _data_to_json(self, data):
        # 把data转换为json数据
        try:
            j = json.dumps(data)
            return j

        except:
            return ""

    # json转换为数据
    def _json_to_data(self, j):
        try:
            data = json.loads(j)
            return data
        except:
            return None

    # 设置一个缓存，json
    def set(self, key, data, ex=3600):
        # self.rds 因为继承了RedisTool，所以自身就有了一个rds属性。self.rds就是redis链接对象
        key = "cache_%s" % key

        try:
            j = self._data_to_json(data)
            self.rds.set(key, j, ex=ex)

            return True

        except Exception as e:
            return False

    # 读取一个缓存
    def get(self, key):
        key = "cache_%s" % key

        json_byte = self.rds.get(key)  # 可能返回两种数据格式  一种是byte类型，另外一种是 None
        if not json_byte:
            return False

        json_str = json_byte.decode()  # 把byte类型的数据转成字符串

        # 解析json
        data = self._json_to_data(json_str)
        if not data:
            return False

        return data

    # 删除一个缓存
    def delete(self, key):
        key = "cache_%s" % key
        self.rds.delete(key)

        return True

    # 清空所有缓存（可以以key的前缀来清空）
    def clear(self, prefix=""):
        prefix = "cache_%s*" % prefix
        keys_list = self.rds.keys(prefix)
        for k in keys_list:
            self.rds.delete(k)
        return True

    # 判断一个缓存是否存在
    def is_exists(self, key):
        key = "cache_%s" % key

        is_exists = self.rds.exists(key)
        if is_exists == 0:
            return False
        else:
            return True


if __name__ == '__main__':
    from app import app

    with app.app_context():
        # class Cat:
        #     name = "张三"

        c = CacheTool()

        # a = c.set("111", ["1", "2", "3"])
        # a = c.set("111222", ["1", "2", "3"])
        # a = c.set("111333", ["1", "2", "3"])
        # a = c.set("222333", ["1", "2", "3"])
        # d = c.clear(prefix="111")
        # print("d", d, type(d))
        # cat = Cat()
        # c.set("111", cat)  # 缓存不可以缓存对象

        c.is_exists("222333")
